package org.nowcoder.leetcode.twoPointers;

/**
 * Title  : 125. Valid Palindrome
 * Source : https://leetcode.cn/problems/valid-palindrome/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-07-10
 */

public class LeetCode_125 {
    public boolean isPalindrome(String s) {
        //常规解法
        // StringBuilder builder = new StringBuilder(s.length());
        // for (int i = 0; i < s.length(); i++) {
        //     char c = s.charAt(i);
        //     //大写字母
        //     if (65 <= c && c <= 90) {
        //         builder.append((char) (c + 32));
        //     }
        //     //小写字母，数字
        //     if ((48 <= c && c <= 57) || (97 <= c && c <= 122)) {
        //         builder.append(c);
        //     }
        // }
        // s = builder.toString();
        // int left = 0, right = s.length() - 1;
        // while (left <= right) {
        //     if (s.charAt(left) != s.charAt(right)){
        //         return false;
        //     }
        //     left++;
        //     right--;
        // }
        // return true;

        //双指针: 一次遍历
        int left = 0, right = s.length() - 1;
        while (left <= right) {
            char lc = s.charAt(left);
            char rc = s.charAt(right);
            if (Character.isUpperCase(lc)) {
                lc = Character.toLowerCase(lc);
            }
            if (Character.isUpperCase(rc)) {
                rc = Character.toLowerCase(rc);
            }
            if (!Character.isLetterOrDigit(lc)) {
                left++;
                continue;
            }
            if (!Character.isLetterOrDigit(rc)) {
                right--;
                continue;
            }
            if (Character.isLetterOrDigit(lc) && Character.isLetterOrDigit(rc) && lc != rc) {
                return false;
            } else {
                left++;
                right--;
            }
        }
        return true;
    }
}
